package com.laxcen.facestaticcheck.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicYuvToRGB;
import android.renderscript.Type;
import android.util.Log;

import com.laxcen.facestaticcheck.core.DetectionResult;

public class NV21ToBitmap {

    private RenderScript rs;
    private ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic;

    public NV21ToBitmap(Context context) {
        rs = RenderScript.create(context);
        yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
    }

    /**
     * 将nv21 流转图片
     * @param nv21
     * @param detectionResult
     * @return
     */
    public Bitmap nv21ToBitmap(byte[] nv21, DetectionResult detectionResult) {
        int width = detectionResult.getWidth();
        int height = detectionResult.getHeight();
        int plusLenth = 30;
        Type.Builder yuvType = new Type.Builder(rs, Element.U8(rs)).setX(nv21.length);
        Allocation in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);
        Type.Builder rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height);
        Allocation out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);
        in.copyFrom(nv21);
        yuvToRgbIntrinsic.setInput(in);
        yuvToRgbIntrinsic.forEach(out);
        Bitmap bmpout = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        out.copyTo(bmpout);
        Matrix matrix = new Matrix();
        matrix.postRotate(-90);
        matrix.postScale(-1, 1);
        Bitmap rotaBitmap1 = Bitmap.createBitmap(bmpout, 0, 0, width, height, matrix, false);
        //只截取人脸那部分
        int left = detectionResult.getLeft();
        if(left-20>=0){
            left = left-20;
        }
        int top = detectionResult.getTop();
        if(top-plusLenth>=0){
            top = top-plusLenth;
        }
        int right=detectionResult.getRight();
        if(right+plusLenth<=detectionResult.getWidth()){
            right=right+plusLenth;
        }
        int bottom=detectionResult.getBottom();
        if(bottom+plusLenth<=detectionResult.getHeight()){
            bottom=bottom+plusLenth;
        }
        int mWidth = width-(left+(width-right));
        int mHeight = height-(top+(height-bottom));
        Bitmap rotaBitmap = Bitmap.createBitmap(rotaBitmap1, left, top, mWidth,mHeight);
        return rotaBitmap;

    }
}
